﻿using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ServiceModel;
using System.Windows;
using System.Windows.Input;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Regions;
using YunBox2.Contracts;
using YunBox2.Contracts.Core;

namespace YunBox2.Client.Infrastructure.ViewModels

{
    [Export(typeof (LoginViewModel))]
    public class LoginViewModel : MainContentViewModel
    {
        private readonly CompositionContainer _container = ClientContext.Current.PrismContainer;
        private readonly DelegateCommand _loginCommmand;
        private readonly ISystemService _systemService = ClientContext.Current.SystemService;
        private string _password;

        [Import]
        private IRegionManager _regionManager;

        private string _userName;

        [ImportingConstructor]
        public LoginViewModel()
        {
            // 在此点下面插入创建对象所需的代码。

            _loginCommmand = new DelegateCommand(Login);
        }


        public override string Title
        {
            get
            {
                return "用户登录";
            }
        }

        public string UserName
        {
            get
            {
                return _userName;
            }
            set
            {
                if (_userName != value)
                {
                    _userName = value;
                    RaisePropertyChanged("UserName");
                }
            }
        }

        public string Password
        {
            get
            {
                return _password;
            }
            set
            {
                if (_password != value)
                {
                    _password = value;
                    RaisePropertyChanged("Password");
                }
            }
        }

        public ICommand LoginCommand
        {
            get
            {
                return _loginCommmand;
            }
        }

        private void Login()
        {
            using (OperationContextScope contextScope = ClientContext.Current.CreateOperationContextScope(_systemService as IContextChannel))
            {
                if (_systemService.Login(UserName, Password))
                {
                    User currentUser = _systemService.GetMyProfile();
                    if (currentUser != null)
                    {
                        currentUser.Password = string.Empty;
                        ClientContext.Current.CurrentUser = currentUser;
                        return;
                    }
                }
                MessageBox.Show("用户登录失败");
            }
        }
    }
}